<?php

namespace helper;

class Arr2Xml
{
    public function arr2xml($arr, $dom = 0, $item = 0, $xmlns = 'urn:ebay:apis:eBLBaseComponents')
    {
        if (!$dom) {
            $dom = new \DOMDocument("1.0", 'utf-8');
        }
        $dom->formatOutput = true; //格式xml输出有换行什么的
        if (!$item) {
            $item = $dom->createElement("ReviseFixedPriceItemRequest");
            $dom->appendChild($item);
            $item->setAttribute('xmlns', $xmlns);//设置属性
        }

        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $itemx = $dom->createElement($key);
                $item->appendChild($itemx);
                if (in_array($key, ['Contact', 'Adult', 'Children'])) {
                    if ($key == 'Contact') {
                        foreach ($val as $k => $v) {
                            $itemx->setAttribute($k, $v);
                        }
                    } else {
                        $item->removeChild($itemx);
                        foreach ($val as $k => $v) {
                            $itemx = $dom->createElement($key);
                            $item->appendChild($itemx);
                            foreach ($v as $kk => $vv) {
                                $itemx->setAttribute($kk, $vv);
                            }
                        }
                    }
                } else {
                    $this->arr2xml($val, $dom, $itemx);
                }
            } else {
                $itemx = $dom->createElement($key, $val);
                $item->appendChild($itemx);
            }
        }
        return $dom->saveXML();
    }
}